package com.knowledge.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.knowledge.common.cache.GlobalLocalCache;
import com.knowledge.common.enums.FavoriteEnum;
import com.knowledge.dao.entity.ArticleFavorite;
import com.knowledge.dao.mapper.ArticleFavoriteMapper;
import com.knowledge.service.ArticleFavoriteService;
import com.knowledge.utils.UserThreadLocal;
import com.knowledge.vo.Result;
import com.knowledge.vo.params.ArticleFavoriteParam;
import com.knowledge.vo.params.FavoriteParam;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Service
public class ArticleFavoriteServiceImpl extends ServiceImpl<ArticleFavoriteMapper, ArticleFavorite> implements ArticleFavoriteService {

    @Resource
    private ArticleFavoriteMapper articleFavoriteMapper;

    @Override
    public Result favorite(FavoriteParam param) {
        //获取当前用户信息
        Long loginUserId = UserThreadLocal.get().getId();
        if (Objects.equals(FavoriteEnum.YES.getStatus(), param.getStatus())) {
            saveFavorite(loginUserId, param.getArticleId());
        }else {
            deleteFavorite(loginUserId, param.getArticleId());
        }
        return Result.success();
    }

    @Override
    public List<ArticleFavorite> listArticleFavorite(ArticleFavoriteParam articleFavoriteParam) {
        QueryWrapper queryWrapper = new QueryWrapper();
        if (articleFavoriteParam.getUserId() != null){
            queryWrapper.eq("user_id", articleFavoriteParam.getUserId());
        }
        if (articleFavoriteParam.getArticleIds() != null && articleFavoriteParam.getArticleIds().size() > 0){
            queryWrapper.in("article_id", articleFavoriteParam.getArticleIds());
        }
        return list(queryWrapper);
    }

    private void deleteFavorite(Long loginUserId, Long articleId) {
        LambdaQueryWrapper<ArticleFavorite> query = Wrappers.lambdaQuery();
        query.eq(ArticleFavorite::getArticleId, articleId);
        query.eq(ArticleFavorite::getUserId, loginUserId);
        articleFavoriteMapper.delete(query);
    }

    private void saveFavorite(Long loginUserId, Long articleId) {
        ArticleFavorite favorite = new ArticleFavorite();
        favorite.setArticleId(articleId);
        favorite.setUserId(loginUserId);
        articleFavoriteMapper.insert(favorite);
    }
}
